import React, {Suspense, use} from 'react';
import DeviceSkeleton from '../DeviceList/DeviceSkeleton';
import {ApiResponse} from '@/services/http';
import {ScrollView} from 'react-native';
import {useSafeAreaInsets} from 'react-native-safe-area-context';

interface AsyncComponentProps<T> {
  children: (data: T) => React.ReactNode;
  promise: Promise<ApiResponse<T>>;
  fallback?: React.ReactNode;
}

// 异步数据组件
const AsyncData = <T,>({
  children,
  promise,
}: {
  children: (data: T) => React.ReactNode;
  promise: Promise<ApiResponse<T>>;
}) => {
  const {data} = use(promise);
  return <>{children(data)}</>;
};

const AsyncComponent = <T,>({
  children,
  promise,
  fallback,
}: AsyncComponentProps<T>) => {
  const {top} = useSafeAreaInsets();
  return (
    <Suspense
      fallback={
        fallback ?? (
          <ScrollView
            contentContainerClassName="px-4 pb-4"
            style={{
              paddingTop: top,
            }}>
            <DeviceSkeleton></DeviceSkeleton>
          </ScrollView>
        )
      }>
      <AsyncData promise={promise}>{children}</AsyncData>
    </Suspense>
  );
};

export default AsyncComponent;
